import { Button,Card,Form,Input,message } from 'antd'
import React from 'react'
import {createApi, getOneById,modifyOne} from '../../../services/messages'
import { useState,useEffect } from 'react'

const { TextArea } = Input;


const Essatedit = (props) => {
  console.log(props);
  //props.match.params.id存在的话表示当前为修改页面，否则为新增页面

  //初始化时执行，取一次数据
  const [form] = Form.useForm();
  useEffect(()=>{
    if(props.match.params.id){
      getOneById(props.match.params.id)
        .then(res=>{
          console.log(res[0])
          form.setFieldsValue({
            essay_title:res[0].essay_title,
            essay_txt:res[0].essay_txt,
            essay_img:res[0].essay_img
          })
        })
    }
 
  },[])



  const onFinish = (values) => {
      console.log('Success:', values);
      if(props.match.params.id){
        modifyOne(props.match.params.id,values)
          .then(res=>{
            props.history.push('/admin/messages')
            message.info('修改成功')
          })
          .catch(err=>{
            console.log(err)
          })
      }else{
        createApi(values)
          .then(res=>{
            props.history.push('/admin/messages')
            message.info('添加成功')
          })
          .catch(err=>{
            console.log(err)
          })
      }

  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Card title='文章编辑'>
      <Form onFinish={onFinish} onFinishFailed={onFinishFailed} form={form}>
        <Form.Item
          name='essay_title' 
          label='题目'
          rules={[{required:true, message:'请输入文章题目'}]}
          >
          <Input placeholder='请输入文章题目' />
        </Form.Item>
        <Form.Item
          name='essay_img' 
          label='图片'
          rules={[{required:true, message:'请输入图片链接'}]}
          >
          <Input placeholder='请输入图片链接' />
        </Form.Item>
        <Form.Item 
          name="essay_txt"
          label='内容'
          rules={[{required:true, message:'请输入文章内容'}]}
          >
          <TextArea placeholder='请输入文章内容' style={{height:300}} />
        </Form.Item>

        <Form.Item>
          <Button htmlType='submit' type='primary' style={{marginLeft:"50%"}}>保存</Button>
        </Form.Item>
      </Form>
    </Card>
  )
}

export default Essatedit